package com.lm.scau.framedemos.Rx;

import android.util.Log;

import rx.Observable;
import rx.Subscriber;
import rx.functions.Action1;

/**
 * Function:
 * auth：liming on 2016/6/29 11:07
 * mail：liming@wxchina.com
 */
public class RxUtils {

    /**
     * RX 打印字符数组
     *
     * @param str
     */
    public void printWords(String[] str) {
        Observable.from(str).subscribe(new Action1<String>() {
            @Override
            public void call(String s) {
                Log.i("printWords", s);
            }
        });
    }

    /**
     * 根据字符查找数组下标,然而并没有什么卵用，因为RX的默认模式是发出和消费都在同一个线程中，所以
     * 这只是一个同步的Rx观察者模式
     *
     * @param word
     * @param source
     */
    public void getWordFromArray(final String word, final String[] source) {
        Observable.create(new Observable.OnSubscribe<Integer>() {
            @Override
            public void call(Subscriber<? super Integer> subscriber) {
                Integer index = -1;
                for (int i = 0; i < source.length; i++) {
                    if (source[i].equals(word)) {
                        index = i;
                    }
                }
                subscriber.onNext(index);
                subscriber.onCompleted();
            }
        }).subscribe(new Subscriber<Integer>() {

            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(Integer integer) {
                if (-1 == integer) {
                    Log.i("onNext", "word not found");
                    return;
                }
                Log.i("onNext", String.valueOf(integer));
            }
        });
    }
}
